package com.atguigu.cart.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.cart.feign.ProductFeignService;
import com.atguigu.cart.interceptor.CartInterceptor;
import com.atguigu.cart.service.CartService;
import com.atguigu.cart.vo.CartItemVo;
import com.atguigu.cart.vo.SkuInfoVo;
import com.atguigu.cart.vo.UserInfoTo;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author bobo
 * @date 2023/7/28
 * @apiNote
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;

    public static final String CART_PREFIX = "gulimall:cart:";
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //1.远程查询当前要添加的商品的信息
        R skuInfo = productFeignService.getSkuInfo(skuId);
        skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>(){});
        return null;
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        //1.判断是否登陆
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            cartKey = CART_PREFIX.concat(String.valueOf(userInfoTo.getUserId()));
        }else {
            cartKey = CART_PREFIX.concat(userInfoTo.getUserKey());
        }

        //redisTemplate.opsForHash().get(cartKey,"1");

        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        return hashOps;
    }
}
